package cn.sanli.manage.controller;

import cn.sanli.manage.ex.ServiceException;

import cn.sanli.manage.pojo.dto.Rewards.PageQueryOfRewardsRequest;
import cn.sanli.manage.pojo.dto.Rewards.RewardsInsertRequest;
import cn.sanli.manage.pojo.dto.Rewards.RewardsUpdateRequest;
import cn.sanli.manage.pojo.entity.Rewards;
import cn.sanli.manage.security.LoginPrincipal;
import cn.sanli.manage.service.RewardsService;
import cn.sanli.manage.utils.DateUtils;
import cn.sanli.manage.utils.StringUtils;
import cn.sanli.manage.web.JsonResult;
import cn.sanli.manage.web.ServiceCode;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 奖励信息表(Rewards)表控制层
 *
 * @author wzy
 * @since 2023-12-07 16:06:41
 */
@RestController
@RequestMapping("/rewards")
@Slf4j
@Api(tags = "奖励信息管理接口")
public class RewardsController {
    /**
     * 服务对象
     */
    @Resource
    private RewardsService rewardsService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryOne")
    @ApiOperation("通过主键查询单条数据")
    public JsonResult<Rewards> queryById(Integer id) {
        log.debug("开始查询id为{}的奖励信息表中的数据", id);
        if(id == null || id == 0) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数不能为空");
        }
        return JsonResult.ok(rewardsService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param rewardsInsertRequest 实体
     * @return 新增结果
     */
    @PostMapping("/insertOne")
    @ApiOperation("新增一条数据")
    public JsonResult<?> add(@RequestBody RewardsInsertRequest rewardsInsertRequest, @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理新增奖励信息请求, 参数: {}", rewardsInsertRequest.toString());
        if(StringUtils.isAnyBlank( rewardsInsertRequest.getName(), rewardsInsertRequest.getNum(),
                rewardsInsertRequest.getReasons(), rewardsInsertRequest.getRewardsDept(),
                rewardsInsertRequest.getRewardsName(), rewardsInsertRequest.getRewardsNum()))
        {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数有误");
        }
        boolean whether = rewardsService.insert(rewardsInsertRequest, loginPrincipal);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "新增数据失败");
        }
        return JsonResult.ok();
    }


    /**     * 修改数据
     *
     * @param updateRequest 实体
     * @return 新增结果
     */
    @PostMapping("/updateOne")
    @ApiOperation("修改一条数据")
    public JsonResult<?> update(@RequestBody RewardsUpdateRequest updateRequest) {
        log.debug("开始处理修改奖励信息请求, 参数: {}", updateRequest.toString());
        if(StringUtils.isAnyBlank(updateRequest.getName(), updateRequest.getNum(),
                updateRequest.getReasons(), updateRequest.getRewardsDept(),
                updateRequest.getRewardsName(), updateRequest.getRewardsNum()))
        {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数有误");
        }
        boolean whether = rewardsService.update(updateRequest);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "修改数据失败");
        }
        return JsonResult.ok();
    }


    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteOne")
    @ApiOperation("根据id删除一条数据")
    public JsonResult<?> deleteById(@ApiParam(name = "id", value = "奖励id", required = true)
                                        @RequestParam Integer id) {
        log.debug("开始删除id为{}的奖励信息表数据", id);
        if(id == null || id == 0) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "参数不匹配");
        }
        boolean whether = rewardsService.deleteById(id);
        if(!whether) {
            throw new ServiceException(ServiceCode.ERROR_DELETE, "根据id删除数据失败");
        }
        return JsonResult.ok();
    }

    /**
     * 根据多条件分页查询奖励信息
     *
     * @param queryRequest 查询条件封装类
     * @return 符合条件的奖励信息集合
     */
    @PostMapping("/pagingQuery")
    @ApiOperation("根据多条件分页查询奖励信息")
    public JsonResult<PageInfo<Rewards>> pagingQuery(@RequestBody PageQueryOfRewardsRequest queryRequest) {
        // 判断时间是否准确, 如果开始时间大于现在时间, 以上方法结果不小于0
        if (queryRequest.getStartTime() != null &&
                queryRequest.getStartTime().getTime() > DateUtils.getNowDate().getTime()) {
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "起始时间不能大于当前时间");
        }
        PageHelper.startPage(queryRequest.getPageNum(), queryRequest.getPageSize());
        List<Rewards> rewards = rewardsService.pagingQuery(queryRequest);
        PageInfo<Rewards> pageInfo = new PageInfo<>(rewards);

        return JsonResult.ok(pageInfo);
    }


    /**
     * 奖惩信息导出到excel表格
     *
     * @param queryRequest 查询条件
     * @param response 响应
     */
    @PostMapping ("/dataEduce")
    @ApiOperation("数据导出excel")
    public void dataEduce(@RequestBody PageQueryOfRewardsRequest queryRequest, HttpServletResponse response)  {
        log.debug("开始处理将数据导出到excel的请求, 请求参数: {}", queryRequest.toString());
        // 先将需要的数据查询出来
        PageHelper.startPage(queryRequest.getPageNum(), queryRequest.getPageSize());
        List<Rewards> rewards = rewardsService.pagingQuery(queryRequest);
        PageInfo<Rewards> pageInfo = new PageInfo<>(rewards);
        log.debug("获取到的奖励信息数据: {}", pageInfo.getList());

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String finalFileName = URLEncoder.encode("奖励信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + finalFileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Rewards.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("")
                    .doWrite(pageInfo.getList());
        } catch (IOException e){
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, "Excel表格导出过程中出现IOException");
        }


    }

}